An introduction to the pyplot interface.
Intro to pyplot露matplotlib.pyplot is a collection of command style functionsthat make matplotlib work like MATLAB.Each pyplot function makessome change to a figure: e.g., creates a figure, creates a plotting areain a figure, plots some lines in a plotting area, decorates the plotwith labels, etc.
In matplotlib.pyplot various states are preservedacross function calls, so that it keeps track of things likethe current figure and plotting area, and the plottingfunctions are directed to the current axes (please note that "axes" hereand in most places in the documentation refers to the axespart of a figureand not the strict mathematical term for more than one axis).
Note
the pyplot API is generally less-flexible than the object-oriented API.Most of the function calls you see here can also be called as methodsfrom an Axes object. We recommend browsing the tutorials andexamples to see how this works.
Generating visualizations with pyplot is very quick:
import matplotlib.pyplot as pltplt.plot([1, 2, 3, 4])plt.ylabel('some numbers')plt.show()You may be wondering why the x-axis ranges from 0-3 and the y-axisfrom 1-4. If you provide a single list or array to theplot() command, matplotlib assumes it is asequence of y values, and automatically generates the x values foryou. Since python ranges start with 0, the default x vector has thesame length as y but starts with 0. Hence the x data are[0,1,2,3].
plot() is a versatile command, and will takean arbitrary number of arguments. For example, to plot x versus y,you can issue the command:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])Out:
[]Formatting the style of your plot露For every x, y pair of arguments, there is an optional third argumentwhich is the format string that indicates the color and line type ofthe plot. The letters and symbols of the format string are fromMATLAB, and you concatenate a color string with a line style string.The default format string is 'b-', which is a solid blue line. Forexample, to plot the above with red circles, you would issue
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')plt.axis([0, 6, 0, 20])plt.show()See the plot() documentation for a completelist of line styles and format strings. Theaxis() command in the example above takes alist of [xmin, xmax, ymin, ymax] and specifies the viewport of theaxes.
If matplotlib were limited to working with lists, it would be fairlyuseless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences areconverted to numpy arrays internally. The example below illustrates aplotting several lines with different format styles in one commandusing arrays.
import numpy as np# evenly sampled time at 200ms intervalst = np.arange(0., 5., 0.2)# red dashes, blue squares and green trianglesplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')plt.show()Plotting with keyword strings露There are some instances where you have data in a format that lets youaccess particular variables with strings. For example, withnumpy.recarray or pandas.DataFrame.
Matplotlib allows you provide such an object withthe data keyword argument. If provided, then you may generate plots withthe strings corresponding to these variables.
data = {'a': np.arange(50),'c': np.random.randint(0, 50, 50),'d': np.random.randn(50)}data['b'] = data['a'] + 10 * np.random.randn(50)data['d'] = np.abs(data['d']) * 100plt.scatter('a', 'b', c='c', s='d', data=data)plt.xlabel('entry a')plt.ylabel('entry b')plt.show()Plotting with categorical variables露It is also possible to create a plot using categorical variables.Matplotlib allows you to pass categorical variables directly tomany plotting functions. For example:
names = ['group_a', 'group_b', 'group_c']values = [1, 10, 100]plt.figure(figsize=(9, 3))plt.subplot(131)plt.bar(names, values)plt.subplot(132)plt.scatter(names, values)plt.subplot(133)plt.plot(names, values)plt.suptitle('Categorical Plotting')plt.show()Controlling line properties露Lines have many attributes that you can set: linewidth, dash style,antialiased, etc; see matplotlib.lines.Line2D. There areseveral ways to set line properties
Use keyword args:
plt.plot(x, y, linewidth=2.0)Use the setter methods of a Line2D instance. plot returns a listof Line2D objects; e.g., line1, line2 = plot(x1, y1, x2, y2). In the codebelow we will suppose that we have onlyone line so that the list returned is of length 1. We use tuple unpacking withline, to get the first element of that list:
line, = plt.plot(x, y, '-')line.set_antialiased(False) # turn off antialiasingUse the setp() command. The example belowuses a MATLAB-style command to set multiple propertieson a list of lines. setp works transparently with a list of objectsor a single object. You can either use python keyword arguments orMATLAB-style string/value pairs:
lines = plt.plot(x1, y1, x2, y2)# use keyword argsplt.setp(lines, color='r', linewidth=2.0)# or MATLAB style string value pairsplt.setp(lines, 'color', 'r', 'linewidth', 2.0)Here are the available Line2D properties.
PropertyValue Typealphafloatanimated[True | False]antialiased or aa[True | False]clip_boxa matplotlib.transform.Bbox instanceclip_on[True | False]clip_patha Path instance and a Transform instance, a Patchcolor or cany matplotlib colorcontainsthe hit testing functiondash_capstyle['butt' | 'round' | 'projecting']dash_joinstyle['miter' | 'round' | 'bevel']dashessequence of on/off ink in pointsdata(np.array xdata, np.array ydata)figurea matplotlib.figure.Figure instancelabelany stringlinestyle or ls[ '-' | '--' | '-.' | ':' | 'steps' | ...]linewidth or lwfloat value in pointsmarker[ '+' | ',' | '.' | '1' | '2' | '3' | '4' ]markeredgecolor or mecany matplotlib colormarkeredgewidth or mewfloat value in pointsmarkerfacecolor or mfcany matplotlib colormarkersize or msfloatmarkevery[ None | integer | (startind, stride) ]pickerused in interactive line selectionpickradiusthe line pick selection radiussolid_capstyle['butt' | 'round' | 'projecting']solid_joinstyle['miter' | 'round' | 'bevel']transforma matplotlib.transforms.Transform instancevisible[True | False]xdatanp.arrayydatanp.arrayzorderany numberTo get a list of settable line properties, call thesetp() function with a line or linesas argument
In [69]: lines = plt.plot([1, 2, 3])In [70]: plt.setp(lines) alpha: float animated: [True | False] antialiased or aa: [True | False] ...snipWorking with multiple figures and axes露MATLAB, and pyplot, have the concept of the currentfigure and the current axes. All plotting commands apply to thecurrent axes. The function gca() returns thecurrent axes (a matplotlib.axes.Axes instance), andgcf() returns the current figure(matplotlib.figure.Figure instance). Normally, you don't haveto worry about this, because it is all taken care of behind thescenes. Below is a script to create two subplots.
def f(t):return np.exp(-t) * np.cos(2*np.pi*t)t1 = np.arange(0.0, 5.0, 0.1)t2 = np.arange(0.0, 5.0, 0.02)plt.figure()plt.subplot(211)plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')plt.subplot(212)plt.plot(t2, np.cos(2*np.pi*t2), 'r--')plt.show()The figure() command here is optional becausefigure(1) will be created by default, just as a subplot(111)will be created by default if you don't manually specify any axes. Thesubplot() command specifies numrows,numcols, plot_number where plot_number ranges from 1 tonumrows*numcols. The commas in the subplot command areoptional if numrows*numcols